#include "producttypes.h"
#include "ui_producttypes.h"
#include "producttypeeditor.h"
#include <QMessageBox>

ProductTypes::ProductTypes(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ProductTypes)
{
    ui->setupUi(this);
}

ProductTypes::~ProductTypes()
{
    delete ui;
}

void ProductTypes::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ProductTypes::loadList()
{
    if (db.isOpen())
        {
        model = new QSqlQueryModel(ui->treeView);
        model->setQuery("SELECT producttypes.ProductTypeID as `Item #` , producttypes.RefNumber as `Ref #`, producttypes.ProductType As `Product Type`, publics.Description FROM pharmacy.producttypes , pharmacy.publics WHERE pharmacy.producttypes.RefNumber = pharmacy.publics.RefNumber");
        ui->treeView->setModel(model);

        ui->treeView->setColumnHidden(0, true);
        }
    else
        {
        QMessageBox::warning(this, "Error", "DB not open");
        }
}

void ProductTypes::setDb(QSqlDatabase newDb)
{
    db = newDb;
    loadList();
}

void ProductTypes::on_pushButtonNew_clicked()
{
    ProductTypeEditor prod(this);
    prod.theMode = "New";
    prod.db = db;
    prod.setMode();
    if (prod.exec())
        loadList();
}

void ProductTypes::on_pushButtonView_clicked()
{
    ProductTypeEditor prod(this);
    prod.theMode = "View";
    QSqlRecord rec = model->record(ui->treeView->currentIndex().row());
    QString hID =  rec.value(0).toString();
    prod.theID = hID;
    prod.db = db;
    prod.setMode();
    if (prod.exec())
        loadList();
}

void ProductTypes::on_pushButtonEdit_clicked()
{
    ProductTypeEditor prod(this);
    prod.theMode = "Edit";
    QSqlRecord rec = model->record(ui->treeView->currentIndex().row());
    QString hID =  rec.value(0).toString();
    prod.theID = hID;
    prod.db = db;
    prod.setMode();
    if (prod.exec())
        loadList();
}

void ProductTypes::on_pushButtonClose_clicked()
{
    this->close();
}

void ProductTypes::on_treeView_doubleClicked(QModelIndex index)
{
    QSqlRecord rec = model->record(index.row());
    QString hID =  rec.value(0).toString();

    ProductTypeEditor prod(this);
    prod.theMode = "Edit";
    prod.theID = hID;
    prod.db = db;
    prod.setMode();
    if (prod.exec())
        loadList();

}
